package com.example.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * @BelongsProject: Java_learning
 * @BelongsPackage: com.example.servlet
 * @Author: song
 * @CreateTime: 2022-12-01  14:06
 * @Description: TODO
 * @Version: 1.0
 */

public class CookiesServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       // 服务器获取多个cookies
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie : cookies) {
            System.out.println(cookie.getName());
        }
        HttpSession session = req.getSession();
        session.setAttribute("name","song");
        String name =(String) session.getAttribute("name");
        System.out.println(name);
        session.removeAttribute("name");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 服务端创建cookie对象
        Cookie cookie = new Cookie("username", "song");
        // 设置cookie访问路径
        cookie.setPath("/Servlet_war_exploded/*");
        // 设置cookies的有效时间
        cookie.setMaxAge(60*60);
        // 将cookie对象响应给客户端
        resp.addCookie(cookie);
    }
}
